import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber    } from 'antd';
import { DictContext } from '../../../context/context';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import DictTag from '../../../components/DictTag';

import { getDeptList, addDept, updateDept, delDept, listDeptExcludeChild, getDept } from '../../../api/system/dept';

function Dept() {
    
    const { useDict, addDateRange, handleTree } = useContext(DictContext);
    const { sys_normal_disable } = useDict('sys_normal_disable');
    const [deptList, setDeptList] = useState([]);
    const [queryParams, setQueryParams] = useState({});
    const [loading, setLoading] = useState(false);
    const [searchForm] = Form.useForm();
    const [open,setOpen] = useState(false);
    const [title,setTitle] = useState('添加部门');
    const [formAdd] = Form.useForm();
    const columns = [
        {
            title: '部门名称',
            dataIndex: 'deptName',
            align: 'center',
            width: 200,
        },
        {
            title: '排序',
            dataIndex: 'orderNum',
            align: 'center',
            width: 100,
        },
        {
            title: '状态',
            dataIndex: 'status',
            align: 'center',
            width: 100,
            render: (text) => {
                return <DictTag code="sys_normal_disable" value={text} options={sys_normal_disable}/>;
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            align: 'center',
            width: 200,
        },
        {
            title: '操作',
            align: 'center',
            width: 200,
            render: (text, record) => {
                return (
                            <Space size="middle">
                            <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
                            <Popconfirm
                                title="删除确认"
                                description={`是否确认删除岗位编号为 ${record.deptId} 的数据项？`}
                                onConfirm={() => handleDelete(record)}
                                onCancel={delCancel}
                                okText="确定"
                                cancelText="取消"
                            >
                            <Button type='link'>删除</Button>
                            </Popconfirm>
                            </Space>
                );
            }
        }];

  useEffect(() => {
    setLoading(true);
    listDept();
  }, [queryParams]);


  function listDept() {
    getDeptList(queryParams).then((res) => {
        const deptTree = handleTree(res.data, 'deptId', 'parentId');
        setDeptList(deptTree);
        setLoading(false);
    });
  }

  const handleAdd = () => {
    setOpen(true);
    setTitle('添加部门');
    formAdd.resetFields();
    
  }

  const handleUpdate = (record) => {
    const deptId = record.deptId;
    getDept(deptId).then((res) => {
        formAdd.setFieldsValue(res.data);
        setOpen(true);
        setTitle('修改部门');
    })
  }

  const handleDelete = (record) => {
    const deptId = record.deptId;
    delDept(deptId).then((res) => {
        if(res?.success) {
            message.success('删除成功');
            listDept();
        }
    })
  }

  const delCancel = () =>{
    //message.info('取消删除');
  }

  const onFinish = (values) => {
    setQueryParams( preState => ({
        ...preState,
        ...values,
      }));
  };

  const handleOk = () => {
    formAdd.validateFields().then((values) => {
        if (formAdd.getFieldValue().deptId === undefined) {
            console.log('=====添加部门======',values);
            addDept(formAdd.getFieldValue()).then((res) => {
                message.success('添加成功');
                setOpen(false);
                listDept();
            });
        } else {
            console.log('=====修改部门======',values);
            updateDept(formAdd.getFieldValue()).then((res) => {
                message.success('修改成功');
                setOpen(false);
                listDept();
            });
        }
    });
  };

  const handleCancel = () =>
  {
      setOpen(false);
  }
  return (
    <div>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
            <Col span={24}>
            <Form form={searchForm} layout="inline" onFinish={onFinish}>
                <Form.Item label="部门名称" name="deptName">
                    <Input placeholder="请输入部门名称" allowClear/>
                </Form.Item>
                <Form.Item label="状态" name="status">
                    <Select placeholder="请选择状态" style={{ width: 120 }} options={sys_normal_disable.value}>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Space>
                    <Button type="primary"  htmlType="submit" icon={<SearchOutlined />} >搜索</Button>
                    <Button type="default" icon={<RedoOutlined />} onClick={() =>{searchForm.resetFields()} }>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
            </Col>
        </Row>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
            <Col span={24}>
            <Space size="middle">
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
            </Space>
            </Col>
        </Row>
        <Table columns={columns} loading={loading} dataSource={deptList} pagination={false} rowKey={(record) => record.deptId} scroll={{y: 500 }}/>
        <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} width={600}>
            <Form form={formAdd} layout="inline">
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={24}>

                <Form.Item label="上级部门" name="parentId">
                    <TreeSelect
                        showSearch
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择上级部门"
                        allowClear
                        treeDefaultExpandAll
                        fieldNames={{ label: 'deptName', value: 'deptId', children: 'children' }} 
                        treeData={deptList}
                    />
                </Form.Item>
                </Col>
                </Row>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={12}>
                <Form.Item label="部门名称" name="deptName" rules={[{ required: true, message: '请输入部门名称' }]}>
                    <Input placeholder="请输入部门名称" />
                </Form.Item>
                </Col>
                <Col span={12}>
                <Form.Item label="排序" name="orderNum" rules={[
                    { required: true, message: '请输入排序' },
                    { pattern: /^[0-9]+$/, message: '请输入数字' }
                ]}>
                    <InputNumber min={0} placeholder="请输入排序" />
                </Form.Item>
                </Col>
                </Row>

                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={12}>
                <Form.Item label="负责人" name="leader">
                    <Input placeholder="请输入负责人" />
                </Form.Item>
                </Col>
                <Col span={12}>
                <Form.Item label="联系电话" name="phone">
                    <Input placeholder="请输入联系电话" />
                </Form.Item>
                </Col>
                </Row>

                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={12}>
                <Form.Item label="邮箱" name="email">
                    <Input placeholder="请输入邮箱" />
                </Form.Item>
                </Col>
                <Col span={12}>
                <Form.Item label="状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
                    <Radio.Group options={sys_normal_disable.value} />
                </Form.Item>
                </Col>
                </Row>
            </Form>
        </Modal>
    </div>
  );
}

export default Dept;